//
//  RLNetworkHelper.m
//  test internet
//
//  Created by 王亚陆 on 15/7/13.
//  Copyright (c) 2015年 王亚陆. All rights reserved.
//

#import "RLNetworkHelper.h"
#import <SystemConfiguration/SystemConfiguration.h>
@implementation RLNetworkHelper
/**
 * 网络是否连通。
 *
 * @return 网络状态枚举值
 * @retval YES 网络通畅
 * @retval NO 网络不通
 */
+ (BOOL)isConnectedToNetwork
{
    // Create zero addy
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;
    //zeroAddress.sin_addr.s_addr = htonl(inet_addr("192.168.1.5"));
    
    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    
    if (!didRetrieveFlags)
    {
        printf("Error. Could not recover network reachability flags\n");
        return NO;
    }
    
    BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0);
    BOOL needsConnection = ((flags & kSCNetworkFlagsConnectionRequired) != 0);
    return (isReachable && !needsConnection) ? YES : NO;
}

/**
 * 检查网络状态。
 *
 *  //Apple NetworkStatus Constant Names.
 *  NotReachable     = kNotReachable, // 不可到达
 *  ReachableViaWiFi = kReachableViaWiFi, //通过WiFi可到达
 *  ReachableViaWWAN = kReachableViaWWAN //通过无线广域网可到达(WWAN，即Wireless Wide Area Network，无线广域网。)，就是3G或2G
 *
 * @return 网络状态枚举值
 * @retval NotReachable 无网络
 * @retval ReachableViaWiFi WIFI网络
 * @retval ReachableViaWWAN 3G/2G网络
 */
+ (NetworkStatus)checkNetworkStatus
{
    
    Reachability *r = [Reachability reachabilityWithHostName:@"www.apple.com"];
    return [r currentReachabilityStatus];
    
}

@end
